<!--基础配置 MaterielBasicConfiguration-->
<template>
  <div class='page_format'>
    <div class="my_Select">
      <el-form :inline="true" class="search-form">
        <el-form-item>
          <el-button class="bt-color-tjd" type="primary" v-if="is_show_button('button_material_config_save')" @click="saveDataForm">添加配置</el-button>
        </el-form-item>
        <el-form-item>
          <el-form-item>
            <el-select v-model="devIcMseries" placeholder="主控平台" clearable style="width:120px;margin-right:6px" @change="handleQuery">
              <el-option
                  v-for="item in devIcMseriesData"
                  :key="item.id"
                  :label="`${item.label}`"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="devScrShape" placeholder="屏幕形状" clearable style="width:120px;margin-right:6px" @change="handleQuery">
              <el-option
                  v-for="item in devScrShapeData"
                  :key="item.id"
                  :label="`${item.label}`"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="devScrDpi" placeholder="分辨率" clearable style="width:120px;margin-right:6px" @change="handleQuery">
              <el-option
                  v-for="item in devScrDpiData"
                  :key="item.id"
                  :label="`${item.label}`"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input style="width:90px;margin-right:8px" size="small" placeholder="配置ID" v-model.number="queryId"
                      clearable></el-input>
          </el-form-item>
          <el-button size="small" @click="handleQuery" icon="el-icon-search" type="primary">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="list" border style="width: 100%">
      <el-table-column type="index" :index="sort" label="序号" width="50"></el-table-column>
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column label="项目品类" align="center">
        <template v-slot="scope">
          <span>{{ getDeviceKindText(scope.row.kind) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="项目类型" align="center">
        <template v-slot="scope">
          <span>{{ getTypeText(scope.row.type) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="devIcMseries" label="主控平台">
        <template v-slot="scope">
          <span>{{ getMasterControlPlatformText(scope.row.devIcMseries) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="devIcMcode" label="主控型号" ></el-table-column>
      <el-table-column prop="devScrShape" label="屏幕形状" align="center">
        <template v-slot="scope">
          <span>{{ getShapeText(scope.row.devScrShape) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="devScrDpi" label="分辨率"></el-table-column>
      <el-table-column prop="devIcFlash" label="Flash规格"></el-table-column>
      <el-table-column prop="reserveSpace" label="预留表盘存储空间(kb)"></el-table-column>
      <el-table-column prop="reserveCount" label="建议表盘个数"></el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column prop="updateBy" label="编辑人" >
        <template v-slot="scope">
          <span>{{ getUserNameText(scope.row.updateBy) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="上传时间" :formatter="formatData"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间" :formatter="formatData"></el-table-column>
      <el-table-column v-if="is_show_button('button_material_config_save')" fixed="right" label="操作" width="100">
        <template v-slot="scope">
          <el-button @click="handleClick(scope.row)" type="text" size="small">编辑</el-button>
          <el-button @click="handleButtonClick(scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="form.id ?'修改配置':'添加配置'" :visible.sync="dialogFormVisible" center @close="closeDialog">
      <el-form :model="form" :rules="rules" ref="dialogForm">
        <el-form-item label="项目品类：" :label-width="formLabelWidth" style="display: inline-block; width: 50%;" prop="kind">
          <el-select v-model="form.kind" placeholder="请选择项目品类" style="width: 100%;">
            <el-option
              v-for="item in deviceKindData"
              :key="item.id"
              :label="`${item.label}`"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目类型：" :label-width="formLabelWidth" style="display: inline-block; width: 50%;"
                      prop="type">
          <el-select v-model="form.type" placeholder="请选择项目类型" style="width: 100%;">
            <el-option
                v-for="item in typeData"
                :key="item.id"
                :label="`${item.label}`"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主控平台系列：" :label-width="formLabelWidth" style="display: inline-block; width: 50%;" prop="devIcMseries">
          <el-select v-model="form.devIcMseries" placeholder="请选择主控平台系列" style="width: 100%;">
            <el-option
                v-for="item in devIcMseriesData"
                :key="item.id"
                :label="`${item.label}`"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主控型号：" :label-width="formLabelWidth" style="display: inline-block; width: 50%;" prop="devIcMcode">
          <el-select v-model="form.devIcMcode" placeholder="请选择主控型号" style="width: 100%;">
            <el-option
                v-for="item in devIcMcodeData"
                :key="item.id"
                :label="`${item.label}`"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="屏幕形状：" :label-width="formLabelWidth" style="display: inline-block; width: 50%;"
                      prop="devScrShape">
          <el-select v-model="form.devScrShape" placeholder="请选择屏幕形状" style="width: 100%;" @change="handleShapeChange">
            <el-option
                v-for="item in devScrShapeData"
                :key="item.id"
                :label="`${item.label}`"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分辨率：" :label-width="formLabelWidth" style="display: inline-block; width: 50%;" prop="devScrDpi">
          <el-select v-model="form.devScrDpi" placeholder="请选择分辨率" style="width: 100%;"  :disabled="displayJudgment">
            <el-option
                v-for="item in devScrDpiData"
                :key="item.id"
                :label="`${item.label}`"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="建议个数：" :label-width="formLabelWidth" style="display: inline-block; width: 50%;"
                      prop="reserveCount">
          <el-input v-model="form.reserveCount" placeholder="请输入建议个数" autocomplete="off" type="number" :disabled="displayJudgment"></el-input>
        </el-form-item>
        <el-form-item label="预留空间(kb)：" :label-width="formLabelWidth" style="display: inline-block; width: 50%;"
                      prop="reserveSpace">
          <el-input v-model="form.reserveSpace" autocomplete="off" placeholder="请输入预留存储空间" type="number" :disabled="displayJudgment"></el-input>
        </el-form-item>
        <el-form-item label="Flash规格：" :label-width="formLabelWidth" style="display: inline-block; width: 50%;"
                      prop="devIcFlash">
          <el-select v-model="form.devIcFlash" placeholder="请选择Flash规格" style="width: 100%;">
            <el-option
              v-for="item in devIcFlashData"
              :key="item.id"
              :label="`${item.label}`"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注：" :label-width="formLabelWidth">
          <el-input v-model="form.remark" placeholder="请输入介绍信息" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" :disabled="submitLoading">取 消</el-button>
        <el-button class="bt-color-tjd" v-if="is_show_button('button_material_config_save')" type="primary"
                   @click="saveDataApi" :loading="submitLoading">确 定
        </el-button>
      </div>
    </el-dialog>
    <Toast :dialogVisible="dialogVisible" @isDelete="deleteDataApi"></Toast>
  </div>
</template>

<script>
import { post } from '@/api/my_axios'
import { changSort } from '@/utils/aqi'

export default {
  name: '',
  data () {
    return {
      displayJudgment: false, // 是否带显示屏判断
      submitLoading: false, // 按钮loading
      dialogFormVisible: false,
      dialogVisible: false,
      dialogShowS: false,
      form: {
        id: '',
        kind: '',
        type: '',
        devIcMseries: '',
        devIcMcode: '',
        devScrShape: '',
        devScrDpi: '',
        devIcFlash: '',
        reserveSpace: '',
        reserveCount: 0,
        remark: ''
      },
      list: [],
      devIcMseriesData: [],
      devScrDpiData: [],
      devIcMcodeData: [],
      devScrShapeData: [], // 屏幕形状
      devIcFlashData: [], // flash存储空间
      deviceKindData: [], // 项目品类
      formLabelWidth: '140px',
      pageSize: 20,
      pageNum: 1,
      total: 0,
      id: '',
      queryValue: '',
      devIcMseries: '',
      devIcMcode: '',
      devScrShape: '',
      devScrDpi: '',
      queryId: '',
      kind: '',
      type: '',
      rules: {
        kind: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        type: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        devIcMseries: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        devIcMcode: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        devScrShape: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        devScrDpi: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        devIcFlash: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        reserveSpace: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        reserveCount: [{ required: true, message: '必填项不能为空！', trigger: 'change' }]
      },
      typeData: [
        { value: 'domestic', label: '国内版（公版）' },
        { value: 'overseas', label: '海外版' }
      ]
    }
  },

  watch: {
    'form.devIcMseries' (val) {
      if (val) {
        this.getSysDictList(val)
      }
    }
  },

  mounted () {
    this.getRoleCascadeRelation()
    this.getDictSortData()
    this.getMaterielBasicConfiguration()
  },

  methods: {
    // 排序 （序号）
    sort (index) {
      return changSort(index, this.pageNum, this.pageSize)
    },

    // 时间格式化
    formatData (time) {
      return new Date(time.createTime).toLocaleString()
    },

    // 无屏幕默认选项
    handleShapeChange () {
      if (this.form.devScrShape === '9') {
        this.displayJudgment = true
        this.form.devScrDpi = '无显示屏' // 自动设置分辨率
        this.form.reserveCount = 0
        this.form.reserveSpace = 0
      } else {
        this.displayJudgment = false
      }
    },

    // 用户名转化
    getUserNameText (value) {
      // 遍历 userCascadeData，查找匹配的 userName，并返回对应的 nickName
      for (const manager of this.userCascadeData) {
        const user = manager.children.find(child => child.value === value)
        if (user) {
          return user.label // 返回对应的 nickName
        }
      }
      return '' // 如果未找到，返回空字符串
    },

    // 主控平台转化
    getMasterControlPlatformText (value) {
      if (value) {
        const devFuncArr = value.split(',')
        const newDevFunc = []
        devFuncArr.forEach(item => {
          this.devIcMseriesData.forEach(ele => {
            if (ele.value === item) newDevFunc.push(ele.label)
          })
        })
        return newDevFunc.join(',')
      }
      return ''
    },

    // 项目品类的转化
    getDeviceKindText (value) {
      // 使用find方法查找特定元素对应的对象
      const selectedItem = this.deviceKindData.find(item => item.value === value)
      // 元素不存在时的处理
      return selectedItem ? selectedItem.label : ''
    },

    // 项目类型转化
    getTypeText (value) {
      const dto = this.typeData.find(v => v.value === value)
      return dto ? dto.label : ''
    },

    // 屏幕转化
    getShapeText (value) {
      const dto = this.devScrShapeData.find(v => v.value === value)
      return dto ? dto.label : ''
    },

    // 新增
    saveDataForm () {
      this.dialogFormVisible = true
      this.form.reserveCount = 0
      this.form.reserveSpace = 0
    },

    // 修改
    handleClick (data) {
      this.dialogFormVisible = true
      Object.keys(data).forEach(key => {
        this.form[key] = data[key]
      })
    },

    // 关闭dialog框
    closeDialog () {
      this.dialogFormVisible = false
      this.submitLoading = false
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
      this.$refs.dialogForm.resetFields()
    },

    getMaterielBasicConfiguration () {
      this.list = []
      const { queryValue, pageSize, pageNum, queryId } = this
      this.$store.dispatch('getMaterielBasicConfiguration', {
        pageSize,
        pageNum,
        queryValue: queryValue,
        id: queryId,
        kind: this.kind,
        type: this.type,
        devIcMseries: this.devIcMseries,
        devIcMcode: this.devIcMcode,
        devScrDpi: this.devScrDpi,
        devIcFlash: this.devIcFlash
      }).then(res => {
        this.list = res.data
        this.total = res.total
      })
    },

    saveDataApi () {
      this.$refs.dialogForm.validate(valid => {
        if (!valid) return false
        this.submitLoading = true
        post('/api/crm/sys/manage/material/configuration/saveInfo', this.form).then(req => {
          if (req && req.code === 200) {
            this.$message({ message: req.msg, type: 'success' })
          } else {
            this.$message({ message: req.msg, type: 'error' })
          }
        }).finally(() => {
          this.closeDialog()
          this.getMaterielBasicConfiguration()
        })
      })
    },

    deleteDataApi (type) {
      if (type === 'ok') {
        post('/api/crm/sys/manage/material/configuration/deleteById', this.id
        ).then(req => {
          if (req && req.code === 200) {
            this.$message({ message: req.msg, type: 'success' })
            this.getMaterielBasicConfiguration()
          }
        })
      }
      this.dialogVisible = false
    },

    // 根据主控平台获取对应主控型号
    getSysDictList (value) {
      this.$store.dispatch('getSysDictItemList', value).then(res => {
        this.devIcMcodeData = res
      })
    },

    // 数据字典配置分类项获取
    getDictSortData (type) {
      // 项目品类
      this.$store.dispatch('getSysDictItemList', 'deviceKind').then(res => {
        this.deviceKindData = res
      })

      // 分辨率
      this.$store.dispatch('getSysDictItemList', 'devScrDpi').then(res => {
        const shieldDp = ['320x380', '410x502', '410x492', '172x320']
        const newArr = []
        res.forEach(item => {
          if (!shieldDp.includes(item.value)) newArr.push(item)
        })
        this.devScrDpiData = newArr
      })

      // 主控平台系列
      this.$store.dispatch('getSysDictItemList', 'devIcMseries').then(res => {
        this.devIcMseriesData = res
      })

      // 屏幕形状
      this.$store.dispatch('getSysDictItemList', 'devScrShape').then(res => {
        this.devScrShapeData = res
      })

      // flash存储空间
      this.$store.dispatch('getSysDictItemList', 'devIcFlash').then(res => {
        this.devIcFlashData = res
      })
    },

    // 用户级联关系
    getRoleCascadeRelation () {
      this.$store.dispatch('getRoleCascadeRelation').then(res => {
        const array = []
        res.forEach(item => {
          if (item.userInfoVOList && item.userInfoVOList.length) {
            array.push({
              value: item.firstLevelId,
              label: item.firstLevelName,
              children: item.userInfoVOList.map(item1 => {
                // 建立 userName 和公司名之间的映射关系
                return {
                  value: item1.userName,
                  label: item1.nickName
                }
              })
            })
          }
        })
        this.userCascadeData = array
      })
    },

    handleQuery () {
      this.pageNum = 1
      this.getMaterielBasicConfiguration()
    },

    handleSizeChange (val) {
      this.pageSize = val
      this.getMaterielBasicConfiguration()
    },

    handleCurrentChange (val) {
      this.pageNum = val
      this.getMaterielBasicConfiguration()
    },

    handleButtonClick (data) {
      this.id = data.id
      this.dialogVisible = true
    },

    is_show_button (name) {
      let show = false
      this.$store.state.module1.menu_list.forEach(v => {
        // eslint-disable-next-line eqeqeq
        if (v.path === name) {
          show = true
        }
      })
      return show
    }
  }
}
</script>

<style lang='scss'>
  .page_format {
    padding: 56px 20px 140px 20px;
  }
  .search-form{
    margin-top: 10px;
  }

  .icon-image {
    width: auto;
    height: auto;
    object-fit: cover;
  }
</style>
